package com.fulihui.information.biz.content.impl.handler;

import com.fulihui.information.biz.content.FullDateManager;
import com.fulihui.information.biz.content.ObtainAppListPageHandler;
import com.fulihui.information.common.config.AppConst;
import com.fulihui.information.core.db.ContentTopDB;
import com.fulihui.information.dto.ContentListItemDTO;
import com.fulihui.information.enums.EDataObtainType;
import com.fulihui.information.request.ContentPageQueryForAppRequest;
import org.near.servicesupport.result.ResultBuilder;
import org.near.servicesupport.result.TPageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.List;

import static org.springframework.util.CollectionUtils.isEmpty;

/**
 * @author Willard.Hu on 2017/1/3 0003.
 */
public abstract class AbstractAppListPageObtainHandler implements ObtainAppListPageHandler {
    protected final transient Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 资讯内容填充管理类
     */
    @Autowired
    private FullDateManager fullDateManager;
    /**
     * 置顶内容存储
     */
    @Autowired
    @Qualifier("redisContentTopDB")
    private ContentTopDB    contentTopDB;

    /**
     * 公共处理模版
     *
     * @see ObtainAppListPageHandler#execute(ContentPageQueryForAppRequest)
     */
    @Override
    public TPageResult<ContentListItemDTO> execute(ContentPageQueryForAppRequest request) {
        List<ContentListItemDTO> list = queryPageList(request);
        // XXX 目前只有热门有置顶
        if (request.getPage() == 1 && // 第一页在第一条插入置顶
                AppConst.CONTENT_HOTS_CATEGORY_CODE.equals(request.getCategoryCode())) {
            ContentListItemDTO top = contentTopDB.getTop(request.getCategoryCode());
            if (list != null && top != null) {
                list.add(0, top);
            }
        }
        // 填充内容
        if (!isEmpty(list)) {
            fullDateManager.fullMulti(list);
        }
        int totalcount = queryTotalCount(request);
        return ResultBuilder.succTPage(list, request.getPage(), request.getRows(), totalcount);
    }

    /**
     * 由子类实现具体的获取列表逻辑
     *
     * @param request {@link ContentPageQueryForAppRequest}
     * @return {@link ContentListItemDTO} 列表
     */
    abstract List<ContentListItemDTO> queryPageList(ContentPageQueryForAppRequest request);

    /**
     * 由子类实现具体的获取查询总数的逻辑
     *
     * @param request {@link ContentPageQueryForAppRequest}
     * @return 查询数据总数量
     */
    abstract int queryTotalCount(ContentPageQueryForAppRequest request);

    /**
     * 数据获取方式
     *
     * @return {@link EDataObtainType}
     */
    public abstract EDataObtainType obtainType();
}
